//
//  GKDetailReusableView.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2020/9/7.
//  Copyright © 2020 wangws1990. All rights reserved.
//

import UIKit
private let view :GKDetailReusableView = GKDetailReusableView.instanceView()
class GKDetailReusableView: UICollectionReusableView {
    @IBOutlet weak var height: NSLayoutConstraint!
    @IBOutlet weak var moreBtn: UIButton!
    @IBOutlet weak var lineview: UIView!
    @IBOutlet weak var contentLab: UILabel!
    class func getHeight(model:GKBookInfo) ->CGFloat{
        view.contentLab.numberOfLines = model.numberLine
        view.content = model.shortIntro
        let cont:NSLayoutConstraint = NSLayoutConstraint.init(item: view, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1.0, constant: SCREEN_WIDTH)
        view.addConstraint(cont)
        let height = view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        view.removeConstraint(cont)
        return height
    }
    var content :String?{
        didSet{
            guard let content = content else { return }
            self.contentLab.attributedText = contentAtt(title: content)
            let height = contentHeight(line: 0)
            let height3 = contentHeight(line: 3)
            self.moreBtn.isHidden = height <= height3
            self.height.constant = self.moreBtn.isHidden ? 0.001 : 30
        }
    }
    func contentAtt(title :String) ->NSAttributedString{
        let content = title.trimmingCharacters(in: .whitespacesAndNewlines);
        let paragraphStyle  = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = .byTruncatingTail
        paragraphStyle.lineSpacing = 4
        paragraphStyle.alignment = .left
        paragraphStyle.allowsDefaultTighteningForTruncation = true
        let att = NSAttributedString.init(string:content.count > 0 ? content : "这家伙很懒,暂无简介!", attributes:[NSAttributedString.Key.paragraphStyle : paragraphStyle])
        return att
    }
    func contentHeight(line : Int) -> CGFloat{
        let titleLab  = UILabel()
        titleLab.attributedText = contentAtt(title: self.content ?? "")
        titleLab.numberOfLines = line
        titleLab.preferredMaxLayoutWidth = SCREEN_WIDTH - 20
        let size : CGSize = titleLab.sizeThatFits(CGSize(width: titleLab.preferredMaxLayoutWidth, height: SCREEN_HEIGHT))
        return size.height
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        self.backgroundColor = UIColor.appxffffff()
        self.contentLab.textColor = UIColor.appx999999()
        self.moreBtn.setTitleColor(moya.appColor, for: .normal)
        self.lineview.backgroundColor = UIColor.appxe5e5e5()
    }
    
}
